package com.yoomiito.app.ui.search

import android.os.Bundle
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.text.TextUtils
import android.view.View
import android.view.WindowManager
import cn.droidlover.xdroidmvp.cache.SharedPref
import cn.droidlover.xdroidmvp.router.Router
import com.chad.library.adapter.base.BaseQuickAdapter
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.yoomiito.app.Constant
import com.yoomiito.app.R
import com.yoomiito.app.base.App
import com.yoomiito.app.base.BaseActivity
import com.yoomiito.app.model.bean.GoodsInfo
import com.yoomiito.app.ui.goods.GoodsInfoActivity
import com.yoomiito.app.utils.AllCode
import com.yoomiito.app.utils.CacheUtils
import com.yoomiito.app.utils.L
import com.yoomiito.app.utils.RouterUtils
import com.yoomiito.app.widget.SpacesItemDecoration
import com.yoomiito.app.widget.state.ContentType
import com.yoomiito.app.widget.state.EmptyType
import com.yoomiito.app.widget.state.StatusManager
import kotlinx.android.synthetic.main.act_search_result.*
import kotlinx.android.synthetic.main.item_search.*
import kotlinx.android.synthetic.main.item_search_toolbar.*

class SearchResultActivity : BaseActivity<SearchResultPresenter>() {
    var mRecyclerView: androidx.recyclerview.widget.RecyclerView? = null
    var mSwipeRefreshLayout: SmartRefreshLayout? = null
    private var goodsAdapter = SearchGoodsAdapter(null)
    private var key: String? = null
    private var sort = ""
    private var hasCoupon = 0
    private var currentPage = 1
    override fun getLayoutId(): Int = R.layout.act_search_result

    override fun newP(): SearchResultPresenter = SearchResultPresenter(App.mAppConfig)

    override fun onStart() {
        super.onStart()
        if (App.mAppConfig.isLogin) p!!.getUserInfo()
    }

    override fun initData(savedInstanceState: Bundle?) {
        mStatusManager = StatusManager.Builder(this)
                .addType(ContentType(R.layout.item_refresh_rcy))
                .addType(EmptyType().setEmptyContent("未找到相关商品"))
                .build()
        mRecyclerView = mStatusManager.view().findViewById(R.id.act_search_result_rcy)
        mSwipeRefreshLayout = mStatusManager.view().findViewById(R.id.act_result_refreshLayout)
        frameLayout.addView(mStatusManager.view())
        key = intent.getStringExtra(Constant.KEY)
        item_search_et.setText(key)
        window.setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
        item_search_del.visibility = View.VISIBLE
        item_search_et.setTextColor(resources.getColor(R.color.color_ff5100))
        initClicks()
        initTabLayout()
        initRcy()
        initRefreshLayout()
    }

    private fun initClicks() {
        act_search_back.setOnClickListener { finish() }
        act_search_search.setOnClickListener {
            key = item_search_et.text.toString().trim { it <= ' ' }
            if (TextUtils.isEmpty(key)) {
                showToast("请输入搜索内容")
                return@setOnClickListener
            }
//            val serachList = SharedPref.getInstance(App.getInstance()).getListData(Constant.HISTORY, String::class.java)
//
//            if (serachList.size >= 5) {
//                for (i in 4 until serachList.size) {
//                    serachList.removeAt(serachList.size - 1)
//                }
//            }
//            if (!serachList.contains(key!!)) {
//                serachList.add(0, key)
//                SharedPref.getInstance(App.getInstance()).putListData(Constant.HISTORY, serachList)
//            }
            key?.let {
                CacheUtils.saveTaoBaoSearchHistory(it)
            }
            currentPage = 1
            mSwipeRefreshLayout!!.autoRefresh()
        }
        item_search_del.setOnClickListener {
            item_search_et.setText("")
            item_search_et.hint = "输入商品名或粘贴淘宝商品名"
        }
    }

    private fun initRefreshLayout() {
        mSwipeRefreshLayout!!.setOnRefreshListener { refreshLayout: RefreshLayout? ->
            currentPage = 1
            p!!.searchGoods(key, sort, hasCoupon, currentPage)
        }
        mSwipeRefreshLayout!!.setOnLoadMoreListener { refreshLayout: RefreshLayout? ->
            currentPage++
            p!!.searchGoods(key, sort, hasCoupon, currentPage)
        }
        mSwipeRefreshLayout!!.autoRefresh()
    }

    private fun initRcy() {
        val layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this, androidx.recyclerview.widget.LinearLayoutManager.VERTICAL, false)
        mRecyclerView!!.layoutManager = layoutManager
        mRecyclerView!!.itemAnimator = androidx.recyclerview.widget.DefaultItemAnimator()
        mRecyclerView!!.addItemDecoration(SpacesItemDecoration(12))
        mRecyclerView!!.adapter = goodsAdapter
        goodsAdapter.onItemClickListener = BaseQuickAdapter.OnItemClickListener { adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int ->
            RouterUtils.toGoodsDetail(this@SearchResultActivity, goodsAdapter.data[position].num_iid.toString(), AllCode.TaoBao)
        }
    }

    private fun initTabLayout() {
        act_result_tabView.setDefault()
//        act_result_tabView.setOnChangeListener { sort: String, hasCoupon: Int ->
//            this@SearchResultActivity.sort = sort
//            this@SearchResultActivity.hasCoupon = hasCoupon
//            currentPage = 1
//            showLoading()
//            mSwipeRefreshLayout?.setNoMoreData(false)
//            p!!.searchGoods(key, sort, hasCoupon, currentPage)
//        }
    }

    fun setData(goodsInfos: List<GoodsInfo?>?) {
        dismissLoading()
        if (currentPage == 1) {
            if (goodsInfos == null || goodsInfos.isEmpty()) {
                mStatusManager.showEmpty()
            } else {
                goodsAdapter.setNewData(goodsInfos)
                mStatusManager.showContent()
            }
            mSwipeRefreshLayout?.finishRefresh(true)
        } else {
            if (goodsInfos == null || goodsInfos.isEmpty()) {
                mSwipeRefreshLayout?.finishLoadMoreWithNoMoreData()
            } else {
                goodsAdapter.addData(goodsInfos)
            }
            mSwipeRefreshLayout?.finishLoadMore(true)
        }
    }

    private fun toDetail(id: String) {
        Router.newIntent(this)
                .putString(Constant.ID, id)
                .to(GoodsInfoActivity::class.java)
                .launch()
    }
}